import { EventEmitter } from 'events'
import { Promise } from 'es6-promise'
import _ from 'lodash'

export let Config = function(Vue) {
  Vue.use(require('vue-resource'));

  // Vue.http.options.root = 'https://www.oschina.net'
  Vue.http.options.root = 'http://localhost:8080'
  Vue.http.options.data = {access_token: 'bbb4beac-cc7f-490b-9e51-adcdaddb8805'}

  Vue.http.interceptors.push({

    request(request) {
      console.log('loading data')
      return request
    },

    response(response) {
      console.log('load finish:', response)
      return response
    }

  })
}

export let Store = function(vm) {


  const store = new EventEmitter()
  const host = 'http://www.oschina.net'

  let cache = {
    'news': [],
    'comments': []
  }

  store.fetchItems = ({category = 3, page = 1, pageSize = 20}) => {
    const action = 'action/openapi/news_list'
    // console.log(Vue.http.options)
    return vm.$http.get(action, {
      catalog: category,
      page: page,
      pageSize: pageSize
    }).then(function ({data: {newslist, notice}}) {
      //将服务器返回数据，转换成我们需要的数据
      return _.map(newslist, news => {
        return {
          id: news.id,
          label: news.title,
          text: news.title,

        }
      })
    })
  }

  store.fetchComments = ({id, catalog, page = 1, pageSize = 20}) => {
    let cmt = cache['comments'][id]
    if (cmt) {
      console.log('读取评论缓存数据：', id)
      return Promise.resolve(cmt)
    }

    const action = 'action/openapi/comment_list'
    return vm.$http.get(action, {
      id, catalog, page, pageSize
    }).then(({data: {commentList}}) => {
      cache['comments'][id] = commentList
      return commentList
    })
  }

  return store
}